package com.explorati.LeetCode046.permute;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 22:09 2020/9/24 0024
 * @ Description ：
 */
public class Solution {

    /**
     * 给定一个 没有重复 数字的序列，返回其所有可能的全排列
     * @param nums
     * @return
     */
    List<List<Integer>> res = new ArrayList<>();
    boolean[] used;
    public List<List<Integer>> permute(int[] nums) {
        if(nums.length == 0) {
            return res;
        }
        used = new boolean[nums.length];
        for(boolean use : used) {
            use = false;
        }
        List<Integer> list = new ArrayList<>();
        generatePermute(nums, 0, list);
        return res;
    }

    /**
     * @param nums  剩余的没遍历到的数
     * @param preList  遍历过的数的集合
     */
    private void generatePermute(int[] nums, int index, List<Integer> preList){
        if(index == nums.length) {
            List<Integer> list = new ArrayList<>(preList.size());
            for(Integer i : preList) {
                Collections.addAll(list, i);
            }
            res.add(list);
            return ;
        }

        for(int i = 0; i < nums.length; i ++) {
            if (!used[i]) {
                preList.add(nums[i]);
                used[i] = true;
                generatePermute(nums, index + 1, preList);
                preList.remove(preList.size() - 1);
                used[i] = false;
            }
        }
        return;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{1, 2, 3};
        List<List<Integer>> res = solution.permute(nums);

        for(List<Integer> list : res) {
            System.out.println(list.toString());
        }
    }
}
